/*
 * @Description: 路由
 * @Author: huacong
 * @Date: 2020-10-30 17:00:05
 * @LastEditTime: 2020-12-02 17:57:22
 * @LastEditors: huacong
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
import { constantRouterMap } from '@/core/routers'
import store from '../store'
import startApp from '@/core/start/startApp'
import config from '../config'

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRouterMap
})

router.onError(error => {
  const pattern = /Loading chunk (\d)+ failed/g
  const isChunkLoadFailed = error.message.match(pattern)
  const targetPath = router.history.pending.fullPath
  if (isChunkLoadFailed) {
    router.replace(targetPath)
  }
})

router.beforeEach(async (to, from, next) => {
  if (store.getters.addRouters.length === 0) {
    startApp(config.chunk, { router, store, to, next })
  } else {
    next()
  }
})

export default router
